package com.ylq.controller;

import com.ylq.entity.Result;
import com.ylq.entity.Roles;
import com.ylq.entity.Users;
import com.ylq.service.RolesService;
import com.ylq.service.UserRolesService;
import com.ylq.service.UsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author qiang
 * @Description TODO
 * @Date 2020-05-01
 **/
@RestController
@Api(description = "【用户角色】相关的操作")
@RequestMapping("/api")
public class UserRolesController {
    @Autowired
    private UserRolesService urSerice;
    @Autowired
    private RolesService rSerice;
    @Autowired
    private UsersService uService;
    @ApiOperation("分配用户（将指定用户添加到角色中）")
    @PostMapping("/AddUserToRole")
    public Object addUserToRole(HttpSession session, @ApiParam("数据库密钥")@RequestParam("token") String token, @ApiParam("用户id")@RequestParam("uId") String uId, @ApiParam("角色id")@RequestParam("rId") String [] rId){
        String getToken = (String) session.getAttribute("token");
        if(getToken.equals(token)){
        //查没有被设置的角色有哪些
        //1、根据用户ID查用户
        //Users byId = uService.findById(uId);
        //2、根据用户ID查可以添加的角色
        List<Roles> otherRoles = rSerice.findOtherRoles(uId);
        //向中间表插入数据
        int i = urSerice.addUserToRole(uId,rId);
        if (i>0){
            return new Result("","添加成功",true);
        }else {
            return new Result("","添加失败",false);
        }

        }else {
            return new Result("", "数据库密钥不匹配", false);
        }
    }
    @ApiOperation("移除用户角色(从角色中移除指定的用户)")
    @PostMapping("/RemoveUserFromRole")
    public Object removeUserFromRole(HttpSession session,@ApiParam("数据库密钥")@RequestParam("token") String token,@ApiParam("用户id")@RequestParam("uId") String uId,@ApiParam("角色id")@RequestParam("rId") String [] rId){
        String getToken = (String) session.getAttribute("token");
        if(getToken.equals(token)){
        //uService.findById(uId);
        List<Roles> otherRoles = rSerice.findOtherRoles(uId);
        int i = urSerice.removeUserFromRole(uId,rId);
        if (i>0){
            return new Result("","移除成功",true);
        }else {
            return new Result("","移除失败",false);
        }

        }else {
            return new Result("", "数据库密钥不匹配", false);
        }

    }

}
